package com.ydlclass.serialize.Impl;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.ydlclass.exceptions.SerializerException;
import com.ydlclass.serialize.Serializer;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Author duWenJian
 * @Date 2023/11/3 15:38
 * @Version 1.0
 */
@Slf4j
public class HessianSerializer implements Serializer {
    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }
        //Hessian序列化
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()){
            Hessian2Output hessian2Output = new Hessian2Output(baos);
            hessian2Output.writeObject(object);
            hessian2Output.flush();
            if (log.isDebugEnabled()){
                log.debug("Hessian序列化成功");
            }
            return baos.toByteArray();
        } catch (IOException e) {
            throw new SerializerException("序列化过程失败");
        }

    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null || clazz == null) {
            return null;
        }
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);){
            Hessian2Input hessian2Input = new Hessian2Input(bais);
            if (log.isDebugEnabled()){
                log.debug("Hessian反序列化成功");
            }
            return (T) hessian2Input.readObject();
        } catch (IOException e) {
            throw new SerializerException("反序列化过程失败");
        }
    }
}
